﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Linq.Expressions;
using System.Web.Routing;

namespace IndoReputation.Commons
{
    public static class LabelExtensions
    {
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes, bool isRequired)
        {
            return LabelFor(html, expression, new RouteValueDictionary(htmlAttributes), isRequired);
        }
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes, bool isRequired)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
            string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
            if (String.IsNullOrEmpty(labelText))
            {
                return MvcHtmlString.Empty;
            }
            var s = string.Empty;


            TagBuilder tag = new TagBuilder("label");
            tag.MergeAttributes(htmlAttributes);
            tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));

            if (isRequired)
            {
                TagBuilder spanRequired = new TagBuilder("span");
                spanRequired.AddCssClass("field-required");
                spanRequired.SetInnerText("*");
                s = spanRequired.ToString(TagRenderMode.Normal);
            }

            TagBuilder span = new TagBuilder("span");
            span.SetInnerText(labelText);
            s += span.ToString(TagRenderMode.Normal);
            
            // assign <span> to <label> inner html
            tag.InnerHtml = s;

            return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
        }

    }
}